﻿using MslDiary.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

// 版权所有：2014  All Rights Reserved.
// 文 件 名：Helper.cs
// 功能描述：
// 创建标识：m.sh.lin0328@163.com 2014/12/6 14:08:34
// 修改描述：
//----------------------------------------------------------------*/
namespace MslDiary.Utils
{
    public class Helper
    {
        private static Helper _instance;
        private static readonly object _lock = new Object();
        private System.Windows.Media.MediaPlayer _player = new System.Windows.Media.MediaPlayer();

        #region 单一实例
        /// <summary>
        /// 
        /// </summary>
        private Helper()
        {

        }

        /// <summary>
        /// 
        /// </summary>
        ~Helper()
        {
            Dispose();
        }
        /// <summary>
        /// 返回唯一实例
        /// </summary>
        public static Helper Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        //if (_instance == null)
                        //{
                        _instance = new Helper();
                        //}
                    }
                }
                return _instance;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            //Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

        #region 进程

        /// <summary>
        /// 杀死进程
        /// </summary>
        /// <param name="proccessName">进程名</param>
        public void EndApp(string proccessName)
        {
            if ((proccessName + "").Length == 0)
            {
                return;
            }
            foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
            {
                if (p.ProcessName == proccessName)
                {
                    try
                    {
                        p.Kill();
                    }
                    catch (Exception e)
                    {
                        MSL.Tool.LogHelper.Instance.WriteLog("Common KillProccess\r\n" + e.ToString());
                    }
                }
            }
        }
        #endregion

        #region CMD

        /// <summary>
        /// 运行cmd命令
        /// </summary>
        /// <param name="command">cmd命令文本</param>
        public void Run(string command)
        {
            if (String.IsNullOrEmpty(command))
                return;
            try
            {
                using (System.Diagnostics.Process p = new System.Diagnostics.Process())
                {
                    p.StartInfo.FileName = "cmd.exe";
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.RedirectStandardInput = true;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.RedirectStandardError = true;
                    p.StartInfo.CreateNoWindow = true;
                    p.Start();
                    //p.StandardInput.WriteLine("shutdown -s -t 30 -c \"如果此时不想关机，就点击“取消关机”按钮！\"");
                    p.StandardInput.WriteLine(command);
                    p.StandardInput.WriteLine("exit");
                    string strRst = p.StandardOutput.ReadToEnd();
                    p.WaitForExit();
                }
            }
            catch (Exception ex)
            {
                MSL.Tool.LogHelper.Instance.WriteLog("Common Run\r\n" + ex.ToString());
            }
        }
        #endregion

        #region 声音

        /// <summary>
        /// 停止播放声音
        /// </summary>
        public void StopAudio()
        {
            System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                if (this._player != null)
                {
                    this._player.Stop();
                    this._player.Close();
                }
            }));
        }
        /// <summary>
        /// 播放声音
        /// </summary>
        /// <param name="soundName">声音名</param>
        public void PalyAudio(string soundPath, double volume)
        {
            if (String.IsNullOrEmpty(soundPath))
                return;

            if (!System.IO.File.Exists(soundPath))
                return;
            /*
              SoundPlayer类特点
              1）仅支持.wav音频文件；
            2）不支持同时播放多个音频（任何新播放的操作将终止当前正在播放的）；
            3）无法控制声音的音量；
              if (path.EndsWith(".wav"))
              {
                  using (System.Media.SoundPlayer player = new System.Media.SoundPlayer(path))
                  {
                      player.Play();//播放波形文件
                  }
              }
            */
            if (this._player != null)
            {
                StopAudio();
            }
            System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                if (soundPath.EndsWith(".mp3") || soundPath.EndsWith(".wma") || soundPath.EndsWith(".wav"))
                {
                    try
                    {
                        this._player = new System.Windows.Media.MediaPlayer();
                        this._player.Open(new Uri(soundPath));
                        this._player.Volume = volume / 100;//大小为0~1.0
                        this._player.Play();
                    }
                    catch (Exception ex)
                    {
                        MSL.Tool.LogHelper.Instance.WriteLog("Core Common_PalyAudio\r\n" + ex.ToString());
                    }
                }
            }));
        }

        #endregion

        #region 获得程序版本

        /// <summary>
        /// 获得程序版本
        /// </summary>
        /// <returns></returns>
        public string GetVersion()
        {
            return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
        }
        #endregion

        #region 启动外部程序

        /// <summary>
        /// 启动外部Windows应用程序
        /// </summary>
        /// <param name="appName">应用程序路径名称</param>
        /// <returns></returns>
        public bool StartApp(string appName)
        {
            return StartApp(appName, null, System.Diagnostics.ProcessWindowStyle.Normal);
        }

        /// <summary>
        /// 启动外部应用程序
        /// </summary>
        /// <param name="appName">应用程序路径名称</param>
        /// <param name="arguments">启动参数</param>
        /// <param name="style">进程窗口模式</param>
        /// <returns></returns>
        public bool StartApp(string appName, string arguments, System.Diagnostics.ProcessWindowStyle style)
        {
            bool result = false;
            using (System.Diagnostics.Process p = new System.Diagnostics.Process())
            {
                p.StartInfo.FileName = appName;//exe,bat and so on
                p.StartInfo.WindowStyle = style;
                p.StartInfo.Arguments = arguments;
                try
                {
                    p.Start();
                    p.WaitForExit();
                    p.Close();
                    result = true;
                }
                catch
                {
                }
            }
            return result;
        }
        #endregion

        #region 传回阳历y年m月的总天数

        /// <summary>
        /// 传回阳历y年m月的总天数
        /// </summary>
        public int GetDaysByMonth(int y, int m)
        {
            int[] days = new int[] { 31, DateTime.IsLeapYear(y) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
            return days[m - 1];
        }
        #endregion

        #region 多个匹配内容

        /// <summary>
        /// 多个匹配内容
        /// </summary>
        /// <param name="input">输入内容</param>
        /// <param name="pattern">表达式字符串</param>
        /// <param name="groupName">分组名, ""代表不分组</param>
        public List<string> GetList(string input, string pattern, string groupName)
        {
            List<string> list = new List<string>();
            Regex re = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);//| RegexOptions.IgnorePatternWhitespace
            MatchCollection mcs = re.Matches(input);
            foreach (Match mc in mcs)
            {
                if (groupName != "")
                {
                    list.Add(mc.Groups[groupName].Value);
                }
                else
                {
                    list.Add(mc.Value);
                }
            }
            return list;
        }

        /// <summary>
        /// 多个匹配内容
        /// </summary>
        /// <param name="input">输入内容</param>
        /// <param name="pattern">表达式字符串</param>
        /// <param name="groupIndex">第几个分组, 从1开始, 0代表不分组</param>
        public List<string> GetList(string input, string pattern, int groupIndex)
        {
            List<string> list = new List<string>();
            Regex re = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
            MatchCollection mcs = re.Matches(input);
            foreach (Match mc in mcs)
            {
                if (groupIndex > 0)
                {
                    list.Add(mc.Groups[groupIndex].Value);
                }
                else
                {
                    list.Add(mc.Value);
                }
            }
            return list;
        }
        #endregion

        #region 信息提醒
        /// <summary>
        /// 默认错误提示
        /// </summary>
        /// <param name="message">显示消息</param>
        public void AlertError(string message)
        {
            ShowMsg(MslDiary.Control.ShowMsgType.Warning, message);
        }
        /// <summary>
        /// 提示信息
        /// </summary>
        /// <param name="message">显示消息</param>
        public void Alert(string message)
        {
            ShowMsg(MslDiary.Control.ShowMsgType.Information, message);
        }
        /// <summary>
        /// 提示警告信息
        /// </summary>
        /// <param name="message">显示消息</param>
        public void AlertWarning(string message)
        {
            ShowMsg(MslDiary.Control.ShowMsgType.Warning, message);
        }
        /// <summary>
        /// 提示成功信息
        /// </summary>
        /// <param name="message">显示消息</param>
        public void AlertSuccess(string message)
        {
            ShowMsg(MslDiary.Control.ShowMsgType.Ok, message);
        }
        /// <summary>
        /// 提示确认信息
        /// </summary>
        /// <param name="title">窗口标题</param>
        /// <param name="message">显示消息</param>
        public void AlertConfirm(string title, string message, Action callback)
        {
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                var window = new Control.ShowMsg(Control.ShowMsgType.Confirm, title, message);
                window.btnAccept.Click += (sender, e) =>
                {
                    window.Close();
                    Loading(callback, "正在处理...");
                    //callback.Invoke();
                };
                window.MouseLeftButtonDown += (sender, e) =>
                {
                    if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
                        window.DragMove();
                };
                window.ShowDialog();
            }));
        }
        /// <summary>
        /// 信息提醒
        /// </summary>
        /// <param name="tipType">提醒类型</param>
        /// <param name="msg">信息</param>
        private void ShowMsg(MslDiary.Control.ShowMsgType tipType, string msg)
        {
            if (Application.Current == null)
                return;

            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                Control.ShowMsg tip = new Control.ShowMsg(tipType, msg);
                switch (tipType)
                {
                    case MslDiary.Control.ShowMsgType.Ok:
                        msg = (String.IsNullOrEmpty(msg) ? msg = "操作成功！" : msg);
                        break;
                    case MslDiary.Control.ShowMsgType.Warning:
                        msg = (String.IsNullOrEmpty(msg) ? msg = msg = "操作失败！" : msg);
                        break;
                    case MslDiary.Control.ShowMsgType.Error:
                        msg = (String.IsNullOrEmpty(msg) ? msg = msg = "操作失败！" : msg);
                        break;
                    case MslDiary.Control.ShowMsgType.Information:
                    default: break;
                }
                tip.Show();
            }));
        }
        #endregion

        #region 加载进度条
        /// <summary>
        /// 加载进度条
        /// </summary>
        /// <param name="doWork">执行方法</param>
        /// <param name="msg">提示</param>
        public void Loading(Action doWork, string msg)
        {
            if (doWork == null)
                return;
            try
            {
                MslDiary.Control.Loading load = new MslDiary.Control.Loading(doWork);
                if (String.IsNullOrEmpty(msg))
                    msg = "正在加载。。。";
                load.Msg = msg;
                load.Start();
                load.ShowDialog();
            }
            catch (Exception)
            {

            }
        }
        #endregion

        #region 弹出Pup窗口提醒
        /// <summary>
        /// 弹出Pup窗口提醒
        /// </summary>
        /// <param name="title">窗口标题</param>
        /// <param name="subject">提醒主题</param>
        /// <param name="msg">信息</param>
        public void ShowPupUp(string title, string subject, string msg)
        {
            if (String.IsNullOrEmpty(title))
                title = "提醒";

            System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                try
                {
                    Control.PopUP pop = new Control.PopUP();
                    pop.Subject = subject;
                    pop.Msg = msg;
                    pop.PopTitle = title;
                    pop.Show();
                }
                catch (System.InvalidOperationException)
                {

                }
            }));
        }
        #endregion

        #region 退出

        public void ExitApp()
        {
            App.Current.Dispatcher.Invoke(new Action(delegate
            {
                NotifyIconHelper.Instance().Hide();
                App.Current.Shutdown();
            }), null);
        }
        #endregion

        #region 清空缓存
        /// <summary>
        /// 清空缓存
        /// </summary>
        public void ClearCachFile()
        {
            GC.Collect();//垃圾回收
            string cmd = String.Format(//清空缓存目录与缓存文件
       @"
@echo off
set path={0}
del /s /f /q '%path%\*.*' 
rd /s/q '%path%\' 
", Gloable.CachePath);
            cmd = cmd.Replace("'", "\"");
            Utils.Helper.Instance.Run(cmd);
        }
        #endregion

        #region 读取配置

        public void ReadConfig()
        {
            MslDiary.Framework.IO.ConfigHelper config = new MslDiary.Framework.IO.ConfigHelper(Gloable.Config);
            Gloable.MinimizeToTray = config.GetValueByKey("MinimizeToTray") == "1" ? true : false;
            Gloable.SaveLog = config.GetValueByKey("SaveLog") == "1" ? true : false;
            Gloable.AutoCheckUpdate = config.GetValueByKey("AutoCheckUpdate") == "1" ? true : false;
            Gloable.IsAutoRun = config.GetValueByKey("IsAutoRun") == "1" ? true : false;
            Gloable.MinimizeToAutoLock = config.GetValueByKey("MinimizeToAutoLock") == "1" ? true : false;
            Gloable.FaceImagePath = Gloable.StartPath + "\\res\\face\\";
            Gloable.CachePath = Gloable.StartPath + "\\cache\\";//缓存文件目录
            Gloable.AppBackgroundImage = config.GetValueByKey("AppBackgroundImage");
            Gloable.EditorBackgroundImage = config.GetValueByKey("EditorBackgroundImage");

            if (String.IsNullOrEmpty(Gloable.AppBackgroundImage))
                Gloable.AppBackgroundImage = "/Theme/Images/Skin/default.jpg";
            if (String.IsNullOrEmpty(Gloable.EditorBackgroundImage))
                Gloable.EditorBackgroundImage = "/Theme/Images/EditorSkin/default.jpg";

            MSL.Tool.IOHelper.Instance.CreateFolder(Gloable.CachePath);
        }
        #endregion

        #region 属性或键盘无操作时长
        public long GetIdleTick()
        {
            LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
            lastInputInfo.cbSize = Marshal.SizeOf(lastInputInfo);
            if (!GetLastInputInfo(ref　lastInputInfo)) return 0;
            return Environment.TickCount - (long)lastInputInfo.dwTime;
        }
        [DllImport("user32.dll")]
        static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
        [StructLayout(LayoutKind.Sequential)]
        private struct LASTINPUTINFO
        {
            [MarshalAs(UnmanagedType.U4)]
            public int cbSize;
            [MarshalAs(UnmanagedType.U4)]
            public uint dwTime;
        }
        #endregion

        #region 设置窗体背景图片

        /// <summary>
        /// 设置窗体背景图片
        /// </summary>
        /// <param name="window"></param>
        /// <param name="imgPath">相对路径</param>
        public void SetWindowBackground(System.Windows.Window window, string imgPath)
        {
            try
            {
                ImageBrush brush = new ImageBrush();
                brush.ImageSource = new BitmapImage(new Uri("pack://application:,,,/MslDiary;component" + imgPath, UriKind.RelativeOrAbsolute));
                brush.TileMode = TileMode.Tile;
                brush.Viewport = new Rect(0, 0, Gloable.MainWindowWidth, 100);
                brush.ViewportUnits = BrushMappingMode.Absolute;
              
                window.Background = brush;
            }
            catch (Exception)
            {

            }
        }
        #endregion

        #region 文件格式
        /// <summary>
        /// 
        /// </summary>
        /// <param name="suffix">文件后缀</param>
        /// <returns></returns>
        public string GetFileType(string suffix)
        {
            suffix = suffix.ToLower();
            if (!suffix.StartsWith(".")) suffix = "." + suffix;
            if (".rar|.zip|.7z|".Contains(suffix + "|")) return "压缩文件|rar";
            if (".txt|".Contains(suffix + "|")) return "文本文本|txt";
            if (".doc|.docx|.xls|.xlsx|.ppt|.pptx|".Contains(suffix + "|")) return "办公文件|doc";
            if (".jpg|.bmp|.png|.gif|".Contains(suffix + "|")) return "图片文件|jpg";
            if (".avi|.mov|.wmv|.3gp|.3gp|.flv|.mpeg|".Contains(suffix + "|")) return "视频文件|avi";
            if (".mp3|.wma|.midi|".Contains(suffix + "|")) return "音频文件|mp3";
            return String.Empty;
        }
        #endregion
    }
}
